<?php

class RegistriesController extends Zend_Controller_Action {

   public function init() {
   }

   public function createAction() {
      $form = new Application_Form_Registry();
      $this->view->form = $form;

      if ($this->getRequest()->isPost()) {
         $formData = $this->getRequest()->getPost();
         if ($form->isValid($formData)) {
            $task_id = (int) $this->getRequest()->getParam('task');
            $data = array(
                'description' => $form->getValue('description'),
                'task_id' => $task_id
            );
            try {
               $registries = new Application_Model_DbTable_Registries();
               $registries->insert($data);
               $this->_helper->flashMessenger->addMessage(
                       array('success' => 'Registry successfully created.'));
            } catch (Exception $exc) {
               $this->_helper->flashMessenger->addMessage(
                       array('error' => $exc->getMessage()));
            }
            $this->_helper->redirector('show', 'tasks', null, array('id' => $task_id));
         } else {
            $form->populate($formData);
         }
      }
   }

   public function updateAction() {
      $form = new Application_Form_Registry();
      $this->view->form = $form;

      if ($this->getRequest()->isPost()) {
         $formData = $this->getRequest()->getPost();
         if ($form->isValid($formData)) {
            $id = (int) $form->getValue('id');
            $task_id = (int) $this->getRequest()->getParam('task');
            $data = array(
                'description' => $form->getValue('description'),
                'task_id' => $task_id,
                'updated_at' => date("Y-m-d h:i:s")
            );
            try {
               $registries = new Application_Model_DbTable_Registries();
               $registries->update($data, 'id = ' . $id);
               $this->_helper->flashMessenger->addMessage(
                       array('success' => 'Registry successfully updated.'));
            } catch (Exception $exc) {
               $this->_helper->flashMessenger->addMessage(
                       array('error' => $exc->getMessage()));
            }
            $this->_helper->redirector('show', 'tasks', null, array('id' => $task_id));
         } else {
            $form->populate($formData);
         }
      } else {
         $id = $this->_getParam('id', 0);
         if ($id > 0) {
            $registries = new Application_Model_DbTable_Registries();
            $form->populate($registries->readRegistry($id));
         }
      }
   }

}

